package com.lt.schoolchat.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lt.schoolchat.common.BaseResponse;
import com.lt.schoolchat.common.ErrorCode;
import com.lt.schoolchat.common.PageRequest;
import com.lt.schoolchat.common.ResultUtils;
import com.lt.schoolchat.exception.BusinessException;
import com.lt.schoolchat.listener.PostImportListener;
import com.lt.schoolchat.model.dto.post.PostExportDTO;
import com.lt.schoolchat.model.dto.post.PostImportDTO;
import com.lt.schoolchat.model.entity.Post;
import com.lt.schoolchat.service.PostService;
import com.lt.schoolchat.service.TagService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: ~Teng~
 * @date: 2023/3/16 11:31
 */
@RestController
@RequestMapping("/excel")
@Slf4j
@Api(tags = "Excel 接口")
public class ExcelController {
    @Resource
    private PostService postService;
    @Resource
    private TagService tagService;

    @PostMapping("/import")
    @ApiOperation("帖子导入")
    public BaseResponse<String> importUserPost(MultipartFile multipartFile) {
        try {
            EasyExcel.read(multipartFile.getInputStream(), PostImportDTO.class, new PostImportListener(postService, tagService))
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .doRead();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "导入失败");
        }
        return ResultUtils.success("导入成功");
    }

    @GetMapping("/export")
    @ApiOperation("帖子导出")
    public BaseResponse<String> exportUserPost(HttpServletResponse response, PageRequest pageRequest) {
        long current = pageRequest.getCurrent();
        long pageSize = pageRequest.getPageSize();
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("帖子", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 分页查询帖子数据
            Page<Post> page = new Page<>(current, pageSize);
            Page<Post> postPage = postService.page(page);
            List<Post> postList = postPage.getRecords();
            List<PostExportDTO> postExportDTOList = postList.stream().map(post -> {
                PostExportDTO postExportDTO = new PostExportDTO();
                BeanUtils.copyProperties(post, postExportDTO);
                return postExportDTO;
            }).collect(Collectors.toList());
            // 导出
            EasyExcel.write(response.getOutputStream(), PostExportDTO.class).sheet("帖子数据").doWrite(postExportDTOList);
        } catch (Exception e) {
            log.error("帖子excel数据导出异常，当前页：{}，每页大小：{}，异常信息：{}", current, pageSize, e.getMessage());
            e.printStackTrace();
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "导出失败");
        }
        return ResultUtils.success("导出成功");
    }
}
